import requests
from requests_toolbelt import MultipartEncoder

from core.error import RequestParameterError


class Http:
    def __init__(self):
        self.requests = requests

    def post(self, *, url: str, data: dict = None, fields: dict = None, headers: dict = None, **kwargs):
        """
        普通数据请求使用data传请求体参数；
        如果需要上传文件请传fields文件。
        fields参数示例：
            fields={
            'pic': (文件名称, 二进制文件IO流, "image/jpg"),
            其余body参数
            }
        """
        if ct := headers.get("content-type"):
            # 统一将content-type转为Content-Type，防止歧义
            headers.pop("content-type")
            headers["Content-Type"] = ct

        if content_type := headers.get("Content-Type"):
            # 根据Content-Type判断请求方式
            if content_type.startswith("application/json"):
                return self.requests.post(url=url, json=data, headers=headers, **kwargs)
            if content_type.startswith("multipart/form-data"):
                if fields is None:
                    raise RequestParameterError("请求参数错误,上传文件需要传fields参数")
                multipart = MultipartEncoder(fields)
                headers["Content_Type"] = multipart.content_type
                return self.requests.post(url=url, data=multipart, headers=headers, **kwargs)
        else:
            return self.requests.post(url=url, data=data, headers=headers, **kwargs)

    def get(self, url, data: dict = None, headers: dict = None, **kwargs):
        return self.requests.get(url=url, params=data, headers=headers, **kwargs)